package vip.xiaonuo.supplier.modular.finance.settlement.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.AbstractRowHeightStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fhs.trans.service.impl.TransService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.util.CommonDownloadUtil;
import vip.xiaonuo.common.util.CommonResponseUtil;

import vip.xiaonuo.supplier.modular.business.businessMain.entity.SupplierBusinessMain;
import vip.xiaonuo.supplier.modular.business.businessMain.service.SupplierBusinessMainService;
import vip.xiaonuo.supplier.modular.custom.objects.entity.SupplierObjects;
import vip.xiaonuo.supplier.modular.custom.objects.mapper.SupplierObjectsMapper;
import vip.xiaonuo.supplier.modular.custom.objects.service.SupplierObjectsService;
import vip.xiaonuo.supplier.modular.finance.account.entity.SupplierAccount;
import vip.xiaonuo.supplier.modular.finance.account.mapper.SupplierAccountMapper;
import vip.xiaonuo.supplier.modular.finance.account.service.SupplierAccountService;
import vip.xiaonuo.supplier.modular.finance.balancelog.entity.SupplierBalanceLog;
import vip.xiaonuo.supplier.modular.finance.balancelog.service.SupplierBalanceLogService;
import vip.xiaonuo.supplier.modular.finance.settlement.entity.SupplierSettlement;
import vip.xiaonuo.supplier.modular.finance.settlement.mapper.SupplierSettlementMapper;
import vip.xiaonuo.supplier.modular.finance.settlement.param.*;
import vip.xiaonuo.supplier.modular.finance.settlement.result.SupplierSettlementExportResult;
import vip.xiaonuo.supplier.modular.finance.settlement.service.SupplierSettlementService;
import vip.xiaonuo.supplier.modular.warehouse.storesstream.entity.SupplierStoresStream;


import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


/**
 * 结算单表Service接口实现类
 *
 * @author Mr.wu
 * @date  2025/04/09 17:28
 **/
@Service
public class SupplierSettlementServiceImpl extends ServiceImpl<SupplierSettlementMapper, SupplierSettlement> implements SupplierSettlementService {

    @Resource
    private SupplierAccountService supplierAccountService;

    @Resource
    private SupplierBusinessMainService supplierBusinessMainService;

    @Resource
    private SupplierObjectsService supplierObjectsService;

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    private static final AtomicInteger sequence = new AtomicInteger(0);

    private static String currentMinute = "";

    @Resource
    private TransService transService;

    @Autowired
    private SupplierAccountMapper supplierAccountMapper;

    @Autowired
    private SupplierObjectsMapper supplierObjectsMapper;

    @Resource
    private SupplierBalanceLogService supplierBalanceLogService;

    @Override
    public Page<SupplierSettlement> page(SupplierSettlementPageParam supplierSettlementPageParam) {
        QueryWrapper<SupplierSettlement> queryWrapper = new QueryWrapper<SupplierSettlement>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(supplierSettlementPageParam.getBusinessCode())){ //结算单号
            queryWrapper.lambda().like(SupplierSettlement::getBusinessCode, supplierSettlementPageParam.getBusinessCode());
        }
        if(ObjectUtil.isNotEmpty(supplierSettlementPageParam.getBusinessBusinessId())) { //业务单号
            queryWrapper.lambda().like(SupplierSettlement::getBusinessBusinessIds, supplierSettlementPageParam.getBusinessBusinessId());
        }
        if(ObjectUtil.isNotEmpty(supplierSettlementPageParam.getBusinessSettlementType())) { //结算类型
            queryWrapper.lambda().eq(SupplierSettlement::getBusinessSettlementType, supplierSettlementPageParam.getBusinessSettlementType());
        }
        if(ObjectUtil.isNotEmpty(supplierSettlementPageParam.getBusinessObjectId())) {//结算对象
            queryWrapper.lambda().eq(SupplierSettlement::getBusinessObjectId, supplierSettlementPageParam.getBusinessObjectId());
        }
        if(ObjectUtil.isNotEmpty(supplierSettlementPageParam.getBusinessShippingStoreId())) {//结算门店
            queryWrapper.lambda().and(i -> i.eq(SupplierSettlement::getBusinessShippingStoreId, supplierSettlementPageParam.getBusinessShippingStoreId()).or().eq(SupplierSettlement::getBusinessStorageStoreId, supplierSettlementPageParam.getBusinessShippingStoreId()));
        }
        if(ObjectUtil.isNotEmpty(supplierSettlementPageParam.getBusinessAccountId())) {//结算账户
            queryWrapper.lambda().eq(SupplierSettlement::getBusinessAccountId, supplierSettlementPageParam.getBusinessAccountId());
        }
        if(ObjectUtil.isNotEmpty(supplierSettlementPageParam.getBusinessProjectId())) {//结算项目
            queryWrapper.lambda().eq(SupplierSettlement::getBusinessProjectId, supplierSettlementPageParam.getBusinessProjectId());
        }
        if(ObjectUtil.isNotEmpty(supplierSettlementPageParam.getBusinessStatus())){ //单据状态
            queryWrapper.lambda().eq(SupplierSettlement::getBusinessStatus, supplierSettlementPageParam.getBusinessStatus());
        }
        //只要结算单或已审核的其它业务单据
        queryWrapper.lambda().and(i -> i.eq(SupplierSettlement::getBusinessType,"JS").or().eq(SupplierSettlement::getBusinessStatus,"1"));
        //查询实付或实收金额大于0的
        queryWrapper.lambda().and(i -> i.ne(SupplierSettlement::getBusinessPayAmount,BigDecimal.ZERO).or().ne(SupplierSettlement::getBusinessInAmount,BigDecimal.ZERO)) ;
        //查询时间范围
        if (ObjectUtil.isNotEmpty(supplierSettlementPageParam.getStartCreateTime()) && ObjectUtil.isNotEmpty(supplierSettlementPageParam.getEndCreateTime())) {
            queryWrapper.lambda().between(SupplierSettlement::getCreateTime, supplierSettlementPageParam.getStartCreateTime() + " 00:00:01", supplierSettlementPageParam.getEndCreateTime() + " 23:59:59");
        }
        //勾选汇总选项
        if(ObjectUtil.isNotEmpty(supplierSettlementPageParam.getIsHavingByType()) && supplierSettlementPageParam.getIsHavingByType()){
            String sqlString = "BUSINESS_SETTLEMENT_TYPE,SUM(BUSINESS_TOTAL_AMOUNT) AS BUSINESS_TOTAL_AMOUNT,SUM(BUSINESS_DISCOUNT_AMOUNT) AS BUSINESS_DISCOUNT_AMOUNT,SUM(BUSINESS_PAY_AMOUNT) AS BUSINESS_PAY_AMOUNT,SUM(BUSINESS_IN_AMOUNT) AS BUSINESS_IN_AMOUNT,BUSINESS_STATUS";
            String groupString = "BUSINESS_SETTLEMENT_TYPE,BUSINESS_STATUS";

            if(ObjectUtil.isNotEmpty(supplierSettlementPageParam.getIsHavingByStore()) && supplierSettlementPageParam.getIsHavingByStore()) {
                sqlString = sqlString + ", BUSINESS_SHIPPING_STORE_ID, BUSINESS_STORAGE_STORE_ID";
                groupString = groupString + ", BUSINESS_SHIPPING_STORE_ID, BUSINESS_STORAGE_STORE_ID";
            }
            if(ObjectUtil.isNotEmpty(supplierSettlementPageParam.getIsHavingByAccount()) && supplierSettlementPageParam.getIsHavingByAccount()) {
                sqlString = sqlString + ", BUSINESS_ACCOUNT_ID";
                groupString = groupString + ", BUSINESS_ACCOUNT_ID";
            }
            if(ObjectUtil.isNotEmpty(supplierSettlementPageParam.getIsHavingByProject()) && supplierSettlementPageParam.getIsHavingByProject()) {
                sqlString = sqlString + ", BUSINESS_PROJECT_ID";
                groupString = groupString + ", BUSINESS_PROJECT_ID";
            }
            if(ObjectUtil.isNotEmpty(supplierSettlementPageParam.getIsHavingByObject()) && supplierSettlementPageParam.getIsHavingByObject()) {
                sqlString = sqlString + ", BUSINESS_OBJECT_ID";
                groupString = groupString + ", BUSINESS_OBJECT_ID";
            }
            queryWrapper.select(sqlString);
            queryWrapper.groupBy(groupString);
        }
        //数据归属
        queryWrapper.lambda().eq(SupplierSettlement::getCompanyId, StpLoginUserUtil.getLoginUser().getCompanyId());
        if(ObjectUtil.isAllNotEmpty(supplierSettlementPageParam.getSortField(), supplierSettlementPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(supplierSettlementPageParam.getSortOrder());
            queryWrapper.orderBy(true, supplierSettlementPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(supplierSettlementPageParam.getSortField()));
        } else {
            //勾选汇总选项
            if(ObjectUtil.isNotEmpty(supplierSettlementPageParam.getIsHavingByType()) && supplierSettlementPageParam.getIsHavingByType()){
                supplierSettlementPageParam.setSortField("businessSettlementType");
                supplierSettlementPageParam.setSortOrder("ascend");
            }else{
                queryWrapper.lambda().orderByAsc(SupplierSettlement::getId);
            }

        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(SupplierSettlementAddParam supplierSettlementAddParam) {
        SupplierSettlement supplierSettlement = BeanUtil.toBean(supplierSettlementAddParam, SupplierSettlement.class);
        //数据归属
        supplierSettlement.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
        //业务类型 -JS-结算单
        supplierSettlement.setBusinessType("JS");
        //单据编号
        Date now = new Date();
        String datePortion = dateFormat.format(now);
        int sequenceNumber = 1;
        if (datePortion.equals(currentMinute)) {
            sequenceNumber = sequence.incrementAndGet();
            if (sequenceNumber > 999) {
                sequence.set(0);
                sequenceNumber = 1;
            }
        } else {
            sequence.set(1);
            currentMinute = datePortion;
        }
        supplierSettlement.setBusinessCode((supplierSettlement.getBusinessSettlementType().equals("0") ? "S" : "F") + datePortion + String.format("%03d", sequenceNumber));

        //如果是收款，则需要把出入库库互换一下
//        if(supplierSettlement.getBusinessSettlementType().equals("0")){
//            supplierSettlement.setBusinessShippingStoreId(supplierSettlementAddParam.getBusinessStorageStoreId());
//            supplierSettlement.setBusinessStorageStoreId(null);
//        }

        //直接审核过账的单据，需要更新收付款账户情况
        if(supplierSettlement.getBusinessStatus().equals("1")){
            //查询收付款账户
            if(ObjectUtil.isNotEmpty(supplierSettlement.getBusinessAccountId())){
                SupplierAccount supplierAccount = supplierAccountService.queryEntity(supplierSettlement.getBusinessAccountId());
                if(ObjectUtil.isNotEmpty(supplierAccount)){
                    //写账户变动日志
                    SupplierBalanceLog supplierBalanceLog = new SupplierBalanceLog();
                    supplierBalanceLog.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
                    supplierBalanceLog.setLogAbstract(supplierSettlement.getBusinessAbstract());//摘要
                    supplierBalanceLog.setLogType("0");//结算账户日志
                    supplierBalanceLog.setLogAccountId(supplierAccount.getId());
                    supplierBalanceLog.setLogBalanceBefore(supplierAccount.getAccountBalance());
                    supplierBalanceLog.setLogBusinessId(supplierSettlement.getId());
                    supplierBalanceLog.setLogBusinessCode(supplierSettlement.getBusinessCode());
                    if(supplierSettlement.getBusinessSettlementType().equals("0")) {//收款
                        supplierBalanceLog.setLogInAmount(supplierSettlement.getBusinessInAmount());
                        supplierBalanceLog.setLogBalanceAfter(supplierAccount.getAccountBalance().add(supplierSettlement.getBusinessInAmount()));
                        supplierBalanceLog.setLogAbstract("余额增加，收入" + supplierSettlement.getBusinessInAmount() + "元,审核过账单据-"+ supplierSettlement.getBusinessCode() +"," + supplierSettlement.getBusinessAbstract());//摘要
                    }else{
                        supplierBalanceLog.setLogPayAmount(supplierSettlement.getBusinessPayAmount());
                        supplierBalanceLog.setLogBalanceAfter(supplierAccount.getAccountBalance().subtract(supplierSettlement.getBusinessPayAmount()));
                        supplierBalanceLog.setLogAbstract("余额减少，支付" + supplierSettlement.getBusinessPayAmount() + "元,审核过账单据-"+ supplierSettlement.getBusinessCode() +"," + supplierSettlement.getBusinessAbstract());//摘要
                    }
                    supplierBalanceLogService.save(supplierBalanceLog);
                    UpdateWrapper<SupplierAccount> supplierAccountUpdateWrapper = new UpdateWrapper<>();
                    supplierAccountUpdateWrapper.eq("id",supplierSettlement.getBusinessAccountId()).setSql("`ACCOUNT_BALANCE`=`ACCOUNT_BALANCE` + " + (supplierSettlement.getBusinessSettlementType().equals("0") ? (supplierSettlement.getBusinessInAmount()) : (BigDecimal.ZERO.subtract(supplierSettlement.getBusinessPayAmount()))) );
                    supplierAccountMapper.update(null, supplierAccountUpdateWrapper);
                }
            }
            //如果有结算对象，处理结算对象的应收或应付
            if(ObjectUtil.isNotEmpty(supplierSettlement.getBusinessObjectId())){
                SupplierObjects supplierObjects = supplierObjectsService.queryEntity(supplierSettlement.getBusinessObjectId());
                if(ObjectUtil.isNotEmpty(supplierObjects)) {
                    //2.1、写结算对象应收应付日志
                    SupplierBalanceLog supplierBalanceLog = new SupplierBalanceLog();
                    supplierBalanceLog.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
                    supplierBalanceLog.setLogType("1");//结算对象应收应付日志
                    supplierBalanceLog.setLogAccountId(supplierObjects.getId());
                    supplierBalanceLog.setLogBalanceBefore(supplierObjects.getObjectAccountsPayable());
                    supplierBalanceLog.setLogBusinessId(supplierSettlement.getId());
                    supplierBalanceLog.setLogBusinessCode(supplierSettlement.getBusinessCode());
                    if(supplierSettlement.getBusinessSettlementType().equals("0")) {//收款
                        supplierBalanceLog.setLogInAmount(supplierSettlement.getBusinessInAmount());
                        supplierBalanceLog.setLogBalanceAfter(supplierObjects.getObjectAccountsPayable().add(supplierSettlement.getBusinessInAmount()));
                        supplierBalanceLog.setLogAbstract("应收减少" + supplierSettlement.getBusinessInAmount() + "元,审核过账单据-"+ supplierSettlement.getBusinessCode() +"," +supplierSettlement.getBusinessAbstract());//摘要
                    }else{
                        supplierBalanceLog.setLogPayAmount(supplierSettlement.getBusinessPayAmount());
                        supplierBalanceLog.setLogBalanceAfter(supplierObjects.getObjectAccountsPayable().subtract(supplierSettlement.getBusinessPayAmount()));
                        supplierBalanceLog.setLogAbstract("应付减少" + supplierSettlement.getBusinessPayAmount() + "元,审核过账单据-"+ supplierSettlement.getBusinessCode() +"," +supplierSettlement.getBusinessAbstract());//摘要
                    }
                    supplierBalanceLogService.save(supplierBalanceLog);
                    //2.2、处理业务对象的总应收应付
                    UpdateWrapper<SupplierObjects> supplierObjectsUpdateWrapper = new UpdateWrapper<>();
                    supplierObjectsUpdateWrapper.eq("id",supplierSettlement.getBusinessObjectId()).setSql("`OBJECT_ACCOUNTS_PAYABLE`=`OBJECT_ACCOUNTS_PAYABLE` + " + (supplierSettlement.getBusinessSettlementType().equals("0") ? supplierSettlement.getBusinessInAmount() : (BigDecimal.ZERO.subtract(supplierSettlement.getBusinessPayAmount()))));
                    supplierObjectsMapper.update(null, supplierObjectsUpdateWrapper);
                }

                //如果销售收入或采购支出的话，需要更新业务单据状态
                //先处理相反类型的抵用数据
                BigDecimal amount = supplierSettlement.getBusinessSettlementType().equals("0") ? supplierSettlement.getBusinessInAmount() : supplierSettlement.getBusinessPayAmount();
                List<SupplierBusinessMain> toUpdateList = new ArrayList<>();
                List<String> businessIds = new ArrayList<>();
                //处理业务主表的结算状态
                LambdaQueryWrapper<SupplierBusinessMain> supplierBusinessMainLambdaQueryWrapper = new LambdaQueryWrapper<>();
                supplierBusinessMainLambdaQueryWrapper.in(SupplierBusinessMain::getBusinessPaymentStatus,("0,2").split(","));//未支付或部分支付
                supplierBusinessMainLambdaQueryWrapper.eq(SupplierBusinessMain::getBusinessStatus,"1");//状态为已审核
                String businessType = supplierSettlementAddParam.getBusinessProjectIdCode().equals("01") ? "EN,RE" : supplierSettlementAddParam.getBusinessProjectIdCode().equals("02") ? "RS" : supplierSettlementAddParam.getBusinessProjectIdCode().equals("05") ? "SO,RS" : supplierSettlementAddParam.getBusinessProjectIdCode().equals("06") ? "RE" : null;
                if(ObjectUtil.isNotEmpty(businessType)){
                    supplierBusinessMainLambdaQueryWrapper.in(SupplierBusinessMain::getBusinessType,businessType.split(","));
                }
                if(ObjectUtil.isNotEmpty(supplierSettlement.getBusinessBusinessIds())){
                    supplierBusinessMainLambdaQueryWrapper.in(SupplierBusinessMain::getId, supplierSettlement.getBusinessBusinessIds().split(","));
                }else{
                    supplierBusinessMainLambdaQueryWrapper.eq(SupplierBusinessMain::getBusinessObjectId, supplierSettlement.getBusinessObjectId());
                }
                //先查询抵扣类单据
                supplierBusinessMainLambdaQueryWrapper.ne(SupplierBusinessMain::getBusinessSettlementType,supplierSettlement.getBusinessSettlementType());
                List<SupplierBusinessMain> supplierBusinessMainList = supplierBusinessMainService.list(supplierBusinessMainLambdaQueryWrapper);
                if(ObjectUtil.isNotEmpty(supplierBusinessMainList)){
                    for(SupplierBusinessMain supplierBusinessMain : supplierBusinessMainList){
                        if(!supplierBusinessMain.getBusinessPaymentStatus().equals("1")){ //如果订单支付状态不是已结算，则去修改订单状态
//                            int result = amount.compareTo(supplierSettlement.getBusinessSettlementType().equals("0") ? (supplierBusinessMain.getBusinessSettlementType().equals(supplierSettlement.getBusinessSettlementType()) ? supplierBusinessMain.getBusinessPendingInAmount() : (BigDecimal.ZERO.subtract(supplierBusinessMain.getBusinessPendingInAmount())) ): (supplierBusinessMain.getBusinessSettlementType().equals(supplierSettlement.getBusinessSettlementType()) ? supplierBusinessMain.getBusinessPendingPayAmount() : (BigDecimal.ZERO.subtract(supplierBusinessMain.getBusinessPendingPayAmount()))));
//                            if(result>=0){//说明钱是够付这笔业务单的
                                amount = amount.add(supplierBusinessMain.getBusinessSettlementType().equals("0") ? supplierBusinessMain.getBusinessPendingInAmount() : supplierBusinessMain.getBusinessPendingPayAmount());//从结算单金额中拿出应付金额，
                                if(supplierBusinessMain.getBusinessSettlementType().equals("0")){
                                    supplierBusinessMain.setBusinessPendingInAmount(BigDecimal.ZERO);//待收金额为0
                                }else{
                                    supplierBusinessMain.setBusinessPendingPayAmount(BigDecimal.ZERO);//待付金额为0
                                }
                                supplierBusinessMain.setBusinessPaymentStatus("1");//已结算
                                businessIds.add(supplierBusinessMain.getId());
                                toUpdateList.add(supplierBusinessMain);//加到批量更新列表中
//                            }
                        }
                    }
//                    supplierBusinessMainService.updateBatchById(toUpdateList);//更新业务主表
                }
                //再处理相同类型的单据
                LambdaQueryWrapper<SupplierBusinessMain> supplierBusinessMainLambdaQueryWrapperA = new LambdaQueryWrapper<>();
                supplierBusinessMainLambdaQueryWrapperA.in(SupplierBusinessMain::getBusinessPaymentStatus,("0,2").split(","));//未支付或部分支付
                supplierBusinessMainLambdaQueryWrapperA.eq(SupplierBusinessMain::getBusinessStatus,"1");//状态为已审核
                String businessTypeA = supplierSettlementAddParam.getBusinessProjectIdCode().equals("01") ? "EN,RE" : supplierSettlementAddParam.getBusinessProjectIdCode().equals("02") ? "RS" : supplierSettlementAddParam.getBusinessProjectIdCode().equals("05") ? "SO,RS" : supplierSettlementAddParam.getBusinessProjectIdCode().equals("06") ? "RE" : null;
                if(ObjectUtil.isNotEmpty(businessTypeA)){
                    supplierBusinessMainLambdaQueryWrapperA.in(SupplierBusinessMain::getBusinessType,businessTypeA.split(","));
                }
                if(ObjectUtil.isNotEmpty(supplierSettlementAddParam.getBusinessBusinessIds())){
                    supplierBusinessMainLambdaQueryWrapperA.in(SupplierBusinessMain::getId, supplierSettlementAddParam.getBusinessBusinessIds().split(","));
                }else{
                    supplierBusinessMainLambdaQueryWrapperA.eq(SupplierBusinessMain::getBusinessObjectId, supplierSettlement.getBusinessObjectId());
                }
                //查询同类业务
                supplierBusinessMainLambdaQueryWrapperA.eq(SupplierBusinessMain::getBusinessSettlementType,supplierSettlement.getBusinessSettlementType());
                List<SupplierBusinessMain> supplierBusinessMainListA = supplierBusinessMainService.list(supplierBusinessMainLambdaQueryWrapperA);
                if(ObjectUtil.isNotEmpty(supplierBusinessMainListA)){
                    for(SupplierBusinessMain supplierBusinessMain : supplierBusinessMainListA){
                        int result = amount.compareTo(supplierBusinessMain.getBusinessSettlementType().equals("0") ? supplierBusinessMain.getBusinessPendingInAmount() : supplierBusinessMain.getBusinessPendingPayAmount());
                        if(result>=0){//说明钱是够付这笔业务单的
                            amount = amount.subtract(supplierBusinessMain.getBusinessSettlementType().equals("0") ? supplierBusinessMain.getBusinessPendingInAmount() : supplierBusinessMain.getBusinessPendingPayAmount());//从结算单金额中拿出应付金额，
                            if(supplierBusinessMain.getBusinessSettlementType().equals("0")){
                                supplierBusinessMain.setBusinessPendingInAmount(BigDecimal.ZERO);//待收金额为0
                            }else{
                                supplierBusinessMain.setBusinessPendingPayAmount(BigDecimal.ZERO);//待付金额为0
                            }
                            supplierBusinessMain.setBusinessPaymentStatus("1");//已结算
                            businessIds.add(supplierBusinessMain.getId());
                            toUpdateList.add(supplierBusinessMain);//加到批量更新列表中
                        }else{ //钱不够，那就有多少付多少
                            if(amount.compareTo(BigDecimal.ZERO) > 0){ //如果还有钱
                                if(supplierBusinessMain.getBusinessSettlementType().equals("0")){
                                    supplierBusinessMain.setBusinessPendingInAmount((supplierSettlement.getBusinessSettlementType().equals("0") ? supplierBusinessMain.getBusinessPendingInAmount() : supplierBusinessMain.getBusinessPendingPayAmount()).subtract(amount));//待付金额=原待付金额 - 这次付的
                                }else{
                                    supplierBusinessMain.setBusinessPendingPayAmount((supplierSettlement.getBusinessSettlementType().equals("0") ? supplierBusinessMain.getBusinessPendingInAmount() : supplierBusinessMain.getBusinessPendingPayAmount()).subtract(amount));//待付金额=原待付金额 - 这次付的
                                }
                                supplierBusinessMain.setBusinessPaymentStatus("2");//部份支付
                                toUpdateList.add(supplierBusinessMain);//加到批量更新列表中
                                amount = BigDecimal.ZERO;//那就梭哈一下，
                                businessIds.add(supplierBusinessMain.getId());
                            }
                        }
                    }
                }
                supplierSettlement.setBusinessBusinessIds(businessIds.stream().map(String::valueOf).collect(Collectors.joining(",")));//把没钱付的业务单号清掉
                supplierBusinessMainService.updateBatchById(toUpdateList);//更新业务主表
                this.save(supplierSettlement);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(SupplierSettlementEditParam supplierSettlementEditParam) {
        SupplierSettlement supplierSettlement = this.queryEntity(supplierSettlementEditParam.getId());
        SupplierSettlement supplierSettlementOld = new SupplierSettlement();
        supplierSettlementOld.setBusinessStatus(supplierSettlement.getBusinessStatus());
        BeanUtil.copyProperties(supplierSettlementEditParam, supplierSettlement);

//        if(supplierSettlement.getBusinessSettlementType().equals("0")){//收款
//            //将入库仓库与出库仓库互换一下
//            supplierSettlement.setBusinessShippingStoreId(supplierSettlementEditParam.getBusinessStorageStoreId());
//            supplierSettlement.setBusinessStorageStoreId(null);
//        }
        //审核过账的单据，需要更新收付款账户情况
        if(supplierSettlement.getBusinessStatus().equals("1") && supplierSettlementOld.getBusinessStatus().equals("0")){
            //查询并处理收付款账户
            if(ObjectUtil.isNotEmpty(supplierSettlement.getBusinessAccountId())){
                SupplierAccount supplierAccount = supplierAccountService.queryEntity(supplierSettlement.getBusinessAccountId());
                if(ObjectUtil.isNotEmpty(supplierAccount)){
                    //写账户变动日志
                    SupplierBalanceLog supplierBalanceLog = new SupplierBalanceLog();
                    supplierBalanceLog.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
                    supplierBalanceLog.setLogAbstract(supplierSettlement.getBusinessAbstract());//摘要
                    supplierBalanceLog.setLogType("0");//结算账户日志
                    supplierBalanceLog.setLogAccountId(supplierAccount.getId());
                    supplierBalanceLog.setLogBalanceBefore(supplierAccount.getAccountBalance());
                    supplierBalanceLog.setLogBusinessId(supplierSettlement.getId());
                    supplierBalanceLog.setLogBusinessCode(supplierSettlement.getBusinessCode());
                    if(supplierSettlement.getBusinessSettlementType().equals("0")) {//收款
                        supplierBalanceLog.setLogInAmount(supplierSettlement.getBusinessInAmount());
                        supplierBalanceLog.setLogBalanceAfter(supplierAccount.getAccountBalance().add(supplierSettlement.getBusinessInAmount()));
                        supplierBalanceLog.setLogAbstract("余额增加，收入" + supplierSettlement.getBusinessInAmount() + "元,审核过账单据-"+ supplierSettlement.getBusinessCode() +"," + supplierSettlement.getBusinessAbstract());//摘要
                    }else{
                        supplierBalanceLog.setLogPayAmount(supplierSettlement.getBusinessPayAmount());
                        supplierBalanceLog.setLogBalanceAfter(supplierAccount.getAccountBalance().subtract(supplierSettlement.getBusinessPayAmount()));
                        supplierBalanceLog.setLogAbstract("余额减少，支付" + supplierSettlement.getBusinessPayAmount() + "元,审核过账单据-"+ supplierSettlement.getBusinessCode() +"," + supplierSettlement.getBusinessAbstract());//摘要
                    }
                    supplierBalanceLogService.save(supplierBalanceLog);
                    UpdateWrapper<SupplierAccount> supplierAccountUpdateWrapper = new UpdateWrapper<>();
                    supplierAccountUpdateWrapper.eq("id",supplierSettlement.getBusinessAccountId()).setSql("`ACCOUNT_BALANCE`=`ACCOUNT_BALANCE` + " + (supplierSettlement.getBusinessSettlementType().equals("0") ? (supplierSettlement.getBusinessInAmount()) : (BigDecimal.ZERO.subtract(supplierSettlement.getBusinessPayAmount()))) );
                    supplierAccountMapper.update(null, supplierAccountUpdateWrapper);
                }
            }
            //如果有结算对象，先冲抵应收应付
            if(ObjectUtil.isNotEmpty(supplierSettlement.getBusinessObjectId())){
                SupplierObjects supplierObjects = supplierObjectsService.queryEntity(supplierSettlement.getBusinessObjectId());
                if(ObjectUtil.isNotEmpty(supplierObjects)){
                    //写结算对象应收应付日志
                    SupplierBalanceLog supplierBalanceLog = new SupplierBalanceLog();
                    supplierBalanceLog.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
                    supplierBalanceLog.setLogType("1");//结算对象应收应付日志
                    supplierBalanceLog.setLogAccountId(supplierObjects.getId());
                    supplierBalanceLog.setLogBalanceBefore(supplierObjects.getObjectAccountsPayable());
                    supplierBalanceLog.setLogBusinessId(supplierSettlement.getId());
                    supplierBalanceLog.setLogBusinessCode(supplierSettlement.getBusinessCode());
                    if(supplierSettlement.getBusinessSettlementType().equals("0")) {//收款
                        supplierBalanceLog.setLogInAmount(supplierSettlement.getBusinessInAmount());
                        supplierBalanceLog.setLogBalanceAfter(supplierObjects.getObjectAccountsPayable().add(supplierSettlement.getBusinessInAmount()));
                        supplierBalanceLog.setLogAbstract("应收减少" + supplierSettlement.getBusinessInAmount() + "元,审核过账单据-"+ supplierSettlement.getBusinessCode() +"," +supplierSettlement.getBusinessAbstract());//摘要
                    }else{
                        supplierBalanceLog.setLogPayAmount(supplierSettlement.getBusinessPayAmount());
                        supplierBalanceLog.setLogBalanceAfter(supplierObjects.getObjectAccountsPayable().subtract(supplierSettlement.getBusinessPayAmount()));
                        supplierBalanceLog.setLogAbstract("应付减少" + supplierSettlement.getBusinessPayAmount() + "元,审核过账单据-"+ supplierSettlement.getBusinessCode() +"," +supplierSettlement.getBusinessAbstract());//摘要
                    }
                    supplierBalanceLogService.save(supplierBalanceLog);
                    UpdateWrapper<SupplierObjects> supplierObjectsUpdateWrapper = new UpdateWrapper<>();
                    supplierObjectsUpdateWrapper.eq("id",supplierSettlement.getBusinessObjectId()).setSql("`OBJECT_ACCOUNTS_PAYABLE`=`OBJECT_ACCOUNTS_PAYABLE` + " + (supplierSettlement.getBusinessSettlementType().equals("0") ? supplierSettlement.getBusinessInAmount() : (BigDecimal.ZERO.subtract(supplierSettlement.getBusinessPayAmount()))));
                    supplierObjectsMapper.update(null, supplierObjectsUpdateWrapper);
                }
                //如果销售收入或采购支出的话，需要更新业务单据状态
                //先处理相反类型的抵用数据
                BigDecimal amount = supplierSettlement.getBusinessSettlementType().equals("0") ? supplierSettlement.getBusinessInAmount() : supplierSettlement.getBusinessPayAmount();
                List<SupplierBusinessMain> toUpdateList = new ArrayList<>();
                List<String> businessIds = new ArrayList<>();
                //处理业务主表的结算状态
                LambdaQueryWrapper<SupplierBusinessMain> supplierBusinessMainLambdaQueryWrapper = new LambdaQueryWrapper<>();
                supplierBusinessMainLambdaQueryWrapper.in(SupplierBusinessMain::getBusinessPaymentStatus,("0,2").split(","));//未支付或部分支付
                supplierBusinessMainLambdaQueryWrapper.eq(SupplierBusinessMain::getBusinessStatus,"1");//状态为已审核
                String businessType = supplierSettlementEditParam.getBusinessProjectIdCode().equals("01") ? "EN,RE" : supplierSettlementEditParam.getBusinessProjectIdCode().equals("02") ? "RS" : supplierSettlementEditParam.getBusinessProjectIdCode().equals("05") ? "SO,RS" : supplierSettlementEditParam.getBusinessProjectIdCode().equals("06") ? "RE" : null;
                if(ObjectUtil.isNotEmpty(businessType)){
                    supplierBusinessMainLambdaQueryWrapper.in(SupplierBusinessMain::getBusinessType,businessType.split(","));
                }
                if(ObjectUtil.isNotEmpty(supplierSettlement.getBusinessBusinessIds())){
                    supplierBusinessMainLambdaQueryWrapper.in(SupplierBusinessMain::getId, supplierSettlement.getBusinessBusinessIds().split(","));
                }else{
                    supplierBusinessMainLambdaQueryWrapper.eq(SupplierBusinessMain::getBusinessObjectId, supplierSettlement.getBusinessObjectId());
                }
                //先查询抵扣类单据
                supplierBusinessMainLambdaQueryWrapper.ne(SupplierBusinessMain::getBusinessSettlementType,supplierSettlement.getBusinessSettlementType());
                List<SupplierBusinessMain> supplierBusinessMainList = supplierBusinessMainService.list(supplierBusinessMainLambdaQueryWrapper);
                if(ObjectUtil.isNotEmpty(supplierBusinessMainList)){
                    for(SupplierBusinessMain supplierBusinessMain : supplierBusinessMainList){
                        if(!supplierBusinessMain.getBusinessPaymentStatus().equals("1")){ //如果订单支付状态不是已结算，则去修改订单状态
//                            int result = amount.compareTo(supplierSettlement.getBusinessSettlementType().equals("0") ? (supplierBusinessMain.getBusinessSettlementType().equals(supplierSettlement.getBusinessSettlementType()) ? supplierBusinessMain.getBusinessPendingInAmount() : (BigDecimal.ZERO.subtract(supplierBusinessMain.getBusinessPendingInAmount())) ): (supplierBusinessMain.getBusinessSettlementType().equals(supplierSettlement.getBusinessSettlementType()) ? supplierBusinessMain.getBusinessPendingPayAmount() : (BigDecimal.ZERO.subtract(supplierBusinessMain.getBusinessPendingPayAmount()))));
//                            if(result>=0){//说明钱是够付这笔业务单的
                            amount = amount.add(supplierBusinessMain.getBusinessSettlementType().equals("0") ? supplierBusinessMain.getBusinessPendingInAmount() : supplierBusinessMain.getBusinessPendingPayAmount());//从结算单金额中拿出应付金额，
                            if(supplierBusinessMain.getBusinessSettlementType().equals("0")){
                                supplierBusinessMain.setBusinessPendingInAmount(BigDecimal.ZERO);//待收金额为0
                            }else{
                                supplierBusinessMain.setBusinessPendingPayAmount(BigDecimal.ZERO);//待付金额为0
                            }
                            supplierBusinessMain.setBusinessPaymentStatus("1");//已结算
                            businessIds.add(supplierBusinessMain.getId());
                            toUpdateList.add(supplierBusinessMain);//加到批量更新列表中
//                            }
                        }
                    }
//                    supplierBusinessMainService.updateBatchById(toUpdateList);//更新业务主表
                }
                //再处理相同类型的单据
                LambdaQueryWrapper<SupplierBusinessMain> supplierBusinessMainLambdaQueryWrapperA = new LambdaQueryWrapper<>();
                supplierBusinessMainLambdaQueryWrapperA.in(SupplierBusinessMain::getBusinessPaymentStatus,("0,2").split(","));//未支付或部分支付
                supplierBusinessMainLambdaQueryWrapperA.eq(SupplierBusinessMain::getBusinessStatus,"1");//状态为已审核
                String businessTypeA = supplierSettlementEditParam.getBusinessProjectIdCode().equals("01") ? "EN,RE" : supplierSettlementEditParam.getBusinessProjectIdCode().equals("02") ? "RS" : supplierSettlementEditParam.getBusinessProjectIdCode().equals("05") ? "SO,RS" : supplierSettlementEditParam.getBusinessProjectIdCode().equals("06") ? "RE" : null;
                if(ObjectUtil.isNotEmpty(businessTypeA)){
                    supplierBusinessMainLambdaQueryWrapperA.in(SupplierBusinessMain::getBusinessType,businessTypeA.split(","));
                }
                if(ObjectUtil.isNotEmpty(supplierSettlementEditParam.getBusinessBusinessIds())){
                    supplierBusinessMainLambdaQueryWrapperA.in(SupplierBusinessMain::getId, supplierSettlementEditParam.getBusinessBusinessIds().split(","));
                }else{
                    supplierBusinessMainLambdaQueryWrapperA.eq(SupplierBusinessMain::getBusinessObjectId, supplierSettlement.getBusinessObjectId());
                }
                //查询同类业务
                supplierBusinessMainLambdaQueryWrapperA.eq(SupplierBusinessMain::getBusinessSettlementType,supplierSettlement.getBusinessSettlementType());
                List<SupplierBusinessMain> supplierBusinessMainListA = supplierBusinessMainService.list(supplierBusinessMainLambdaQueryWrapperA);
                if(ObjectUtil.isNotEmpty(supplierBusinessMainListA)){
                    for(SupplierBusinessMain supplierBusinessMain : supplierBusinessMainListA){
                        int result = amount.compareTo(supplierBusinessMain.getBusinessSettlementType().equals("0") ? supplierBusinessMain.getBusinessPendingInAmount() : supplierBusinessMain.getBusinessPendingPayAmount());
                        if(result>=0){//说明钱是够付这笔业务单的
                            amount = amount.subtract(supplierBusinessMain.getBusinessSettlementType().equals("0") ? supplierBusinessMain.getBusinessPendingInAmount() : supplierBusinessMain.getBusinessPendingPayAmount());//从结算单金额中拿出应付金额，
                            if(supplierBusinessMain.getBusinessSettlementType().equals("0")){
                                supplierBusinessMain.setBusinessPendingInAmount(BigDecimal.ZERO);//待收金额为0
                            }else{
                                supplierBusinessMain.setBusinessPendingPayAmount(BigDecimal.ZERO);//待付金额为0
                            }
                            supplierBusinessMain.setBusinessPaymentStatus("1");//已结算
                            businessIds.add(supplierBusinessMain.getId());
                            toUpdateList.add(supplierBusinessMain);//加到批量更新列表中
                        }else{ //钱不够，那就有多少付多少
                            if(amount.compareTo(BigDecimal.ZERO) > 0){ //如果还有钱
                                if(supplierBusinessMain.getBusinessSettlementType().equals("0")){
                                    supplierBusinessMain.setBusinessPendingInAmount((supplierSettlement.getBusinessSettlementType().equals("0") ? supplierBusinessMain.getBusinessPendingInAmount() : supplierBusinessMain.getBusinessPendingPayAmount()).subtract(amount));//待付金额=原待付金额 - 这次付的
                                }else{
                                    supplierBusinessMain.setBusinessPendingPayAmount((supplierSettlement.getBusinessSettlementType().equals("0") ? supplierBusinessMain.getBusinessPendingInAmount() : supplierBusinessMain.getBusinessPendingPayAmount()).subtract(amount));//待付金额=原待付金额 - 这次付的
                                }
                                supplierBusinessMain.setBusinessPaymentStatus("2");//部份支付
                                toUpdateList.add(supplierBusinessMain);//加到批量更新列表中
                                amount = BigDecimal.ZERO;//那就梭哈一下，
                                businessIds.add(supplierBusinessMain.getId());
                            }
                        }
                    }
                }
                supplierSettlement.setBusinessBusinessIds(businessIds.stream().map(String::valueOf).collect(Collectors.joining(",")));//把没钱付的业务单号清掉
                supplierBusinessMainService.updateBatchById(toUpdateList);//更新业务主表
            }
        }else{
            supplierSettlement.setBusinessAccountBalanceBefore(BigDecimal.ZERO);
            supplierSettlement.setBusinessAccountBalanceAfter(BigDecimal.ZERO);
        }
        //如果是反审核单据
        if(supplierSettlement.getBusinessStatus().equals("0") && supplierSettlementOld.getBusinessStatus().equals("1")){
            //先处理收付款账户
            if(ObjectUtil.isNotEmpty(supplierSettlement.getBusinessAccountId())){
                SupplierAccount supplierAccount = supplierAccountService.queryEntity(supplierSettlement.getBusinessAccountId());
//                supplierAccount.setAccountBalance(supplierAccount.getAccountBalance().add((supplierSettlement.getBusinessSettlementType().equals("0") ? (BigDecimal.ZERO.subtract(supplierSettlement.getBusinessInAmount())) : supplierSettlement.getBusinessPayAmount())));
//                supplierAccountService.updateById(supplierAccount);//更新收款账户余额
                //写账户变动日志
                SupplierBalanceLog supplierBalanceLog = new SupplierBalanceLog();
                supplierBalanceLog.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
                supplierBalanceLog.setLogAbstract(supplierSettlement.getBusinessAbstract());//摘要
                supplierBalanceLog.setLogType("0");//结算账户日志
                supplierBalanceLog.setLogAccountId(supplierAccount.getId());
                supplierBalanceLog.setLogBalanceBefore(supplierAccount.getAccountBalance());
                supplierBalanceLog.setLogBusinessId(supplierSettlement.getId());
                supplierBalanceLog.setLogBusinessCode(supplierSettlement.getBusinessCode());
                if(supplierSettlement.getBusinessSettlementType().equals("0")) {//收款
                    supplierBalanceLog.setLogInAmount(BigDecimal.ZERO.subtract(supplierSettlement.getBusinessInAmount()));
                    supplierBalanceLog.setLogBalanceAfter(supplierAccount.getAccountBalance().subtract(supplierSettlement.getBusinessInAmount()));
                    supplierBalanceLog.setLogAbstract("余额减少" + supplierSettlement.getBusinessInAmount() + "元,反审核单据-"+ supplierSettlement.getBusinessCode() +","  + supplierSettlement.getBusinessAbstract());//摘要
                }else{
                    supplierBalanceLog.setLogPayAmount(BigDecimal.ZERO.subtract(supplierSettlement.getBusinessPayAmount()));
                    supplierBalanceLog.setLogBalanceAfter(supplierAccount.getAccountBalance().add(supplierSettlement.getBusinessPayAmount()));
                    supplierBalanceLog.setLogAbstract("余额增加" + supplierSettlement.getBusinessPayAmount() + "元,反审核单据-"+ supplierSettlement.getBusinessCode() +"," + supplierSettlement.getBusinessAbstract());//摘要
                }
                supplierBalanceLogService.save(supplierBalanceLog);
                UpdateWrapper<SupplierAccount> supplierAccountUpdateWrapper = new UpdateWrapper<>();
                supplierAccountUpdateWrapper.eq("id",supplierSettlement.getBusinessAccountId()).setSql("`ACCOUNT_BALANCE`=`ACCOUNT_BALANCE` + " + (supplierSettlement.getBusinessSettlementType().equals("0") ? (BigDecimal.ZERO.subtract(supplierSettlement.getBusinessInAmount())) : supplierSettlement.getBusinessPayAmount()) );
                supplierAccountMapper.update(null, supplierAccountUpdateWrapper);
            }

            //如果有结算结象，则需要处理业务对象的应收应付
            if(ObjectUtil.isNotEmpty(supplierSettlement.getBusinessObjectId())){
                //冲抵应收应付
                SupplierObjects supplierObjects = supplierObjectsService.queryEntity(supplierSettlement.getBusinessObjectId());
                if(ObjectUtil.isNotEmpty(supplierObjects)){
                    //写结算对象应收应付日志
                    SupplierBalanceLog supplierBalanceLog = new SupplierBalanceLog();
                    supplierBalanceLog.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
                    supplierBalanceLog.setLogType("1");//结算对象应收应付日志
                    supplierBalanceLog.setLogAccountId(supplierObjects.getId());
                    supplierBalanceLog.setLogBalanceBefore(supplierObjects.getObjectAccountsPayable());
                    supplierBalanceLog.setLogBusinessId(supplierSettlement.getId());
                    supplierBalanceLog.setLogBusinessCode(supplierSettlement.getBusinessCode());
                    if(supplierSettlement.getBusinessSettlementType().equals("0")) {//收款
                        supplierBalanceLog.setLogInAmount(BigDecimal.ZERO.subtract(supplierSettlement.getBusinessInAmount()));
                        supplierBalanceLog.setLogBalanceAfter(supplierObjects.getObjectAccountsPayable().subtract(supplierSettlement.getBusinessInAmount()));
                        supplierBalanceLog.setLogAbstract("应收增加" + supplierSettlement.getBusinessInAmount() + "元,反审核单据-"+ supplierSettlement.getBusinessCode() +"," +supplierSettlement.getBusinessAbstract());//摘要
                    }else{
                        supplierBalanceLog.setLogPayAmount(BigDecimal.ZERO.subtract(supplierSettlement.getBusinessPayAmount()));
                        supplierBalanceLog.setLogBalanceAfter(supplierObjects.getObjectAccountsPayable().add(supplierSettlement.getBusinessPayAmount()));
                        supplierBalanceLog.setLogAbstract("应付增加" + supplierSettlement.getBusinessPayAmount() + "元,反审核单据-"+ supplierSettlement.getBusinessCode() +"," +supplierSettlement.getBusinessAbstract());//摘要
                    }
                    supplierBalanceLogService.save(supplierBalanceLog);
                    UpdateWrapper<SupplierObjects> supplierObjectsUpdateWrapper = new UpdateWrapper<>();
                    supplierObjectsUpdateWrapper.eq("id",supplierSettlement.getBusinessObjectId()).setSql("`OBJECT_ACCOUNTS_PAYABLE`=`OBJECT_ACCOUNTS_PAYABLE` + " + (supplierSettlement.getBusinessSettlementType().equals("0") ? (BigDecimal.ZERO.subtract(supplierSettlement.getBusinessInAmount())) : supplierSettlement.getBusinessPayAmount()));
                    supplierObjectsMapper.update(null, supplierObjectsUpdateWrapper);
                }
            }

            //如果有业务单据的的话，需要处理业务单据更新业务单据结算状态
            if(ObjectUtil.isNotEmpty(supplierSettlement.getBusinessBusinessIds())){
                //同类业务，冲抵类业务不处理
                List<SupplierBusinessMain> supplierBusinessMainList = supplierBusinessMainService.list(new LambdaQueryWrapper<SupplierBusinessMain>().eq(SupplierBusinessMain::getBusinessSettlementType,supplierSettlement.getBusinessSettlementType()).in(SupplierBusinessMain::getId, supplierSettlement.getBusinessBusinessIds().split(",")));
                BigDecimal amount = supplierSettlement.getBusinessSettlementType().equals("0") ? supplierSettlement.getBusinessInAmount() : supplierSettlement.getBusinessPayAmount();
                if(ObjectUtil.isNotEmpty(supplierBusinessMainList)){
                    List<SupplierBusinessMain> toUpdateList = new ArrayList<SupplierBusinessMain>();
                    List<String> businessIds = new ArrayList<>();
                    for(SupplierBusinessMain supplierBusinessMain : supplierBusinessMainList){
                        int result = amount.compareTo(supplierBusinessMain.getBusinessSettlementType().equals("0") ? supplierBusinessMain.getBusinessReceivableAmount() : supplierBusinessMain.getBusinessPayableAmount());
                        if(result>=0){ //金额够全额退款的
                            if(supplierSettlement.getBusinessSettlementType().equals("0")){//收款单
                                supplierBusinessMain.setBusinessPendingInAmount(supplierBusinessMain.getBusinessReceivableAmount());
                                supplierBusinessMain.setBusinessInAmount(BigDecimal.ZERO);
                            }else{//付款单
                                supplierBusinessMain.setBusinessPendingPayAmount(supplierBusinessMain.getBusinessPayableAmount());
                                supplierBusinessMain.setBusinessPayAmount(BigDecimal.ZERO);
                            }
                            supplierBusinessMain.setBusinessPaymentStatus("0");//未结算
                            toUpdateList.add(supplierBusinessMain);//加到批量更新列表中
                            businessIds.add(supplierBusinessMain.getId());
                            amount = amount.subtract(supplierSettlement.getBusinessSettlementType().equals("0") ? supplierBusinessMain.getBusinessReceivableAmount() : supplierBusinessMain.getBusinessPayableAmount());
                        }else{
                            if(amount.compareTo(BigDecimal.ZERO) > 0){
                                if(supplierSettlement.getBusinessSettlementType().equals("0")){//收款单
                                    supplierBusinessMain.setBusinessPendingInAmount(supplierBusinessMain.getBusinessPendingInAmount().add(amount));
                                }else{//付款单
                                    supplierBusinessMain.setBusinessPendingPayAmount(supplierBusinessMain.getBusinessPendingPayAmount().add(amount));
                                }
                                supplierBusinessMain.setBusinessPaymentStatus("2");//未结算
                                toUpdateList.add(supplierBusinessMain);//加到批量更新列表中
                                amount = BigDecimal.ZERO;
                                businessIds.add(supplierBusinessMain.getId());
                            }
                        }
                    }
                    supplierSettlement.setBusinessBusinessIds(businessIds.stream().map(String::valueOf).collect(Collectors.joining(",")));//把没钱付的业务单号清掉
                    supplierBusinessMainService.updateBatchById(toUpdateList);//更新业务主表
                }
            }
        }
        this.updateById(supplierSettlement);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<SupplierSettlementIdParam> supplierSettlementIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(supplierSettlementIdParamList, SupplierSettlementIdParam::getId));
    }

    @Override
    public SupplierSettlement detail(SupplierSettlementIdParam supplierSettlementIdParam) {
        return this.queryEntity(supplierSettlementIdParam.getId());
    }

    @Override
    public SupplierSettlement queryEntity(String id) {
        SupplierSettlement supplierSettlement = this.getById(id);
        if(ObjectUtil.isEmpty(supplierSettlement)) {
            throw new CommonException("结算单表不存在，id值为：{}", id);
        }
        return supplierSettlement;
    }

    @Override
    public void exportSettlement(SupplierSettlementExportParam supplierSettlementExportParam, HttpServletResponse response) throws IOException {
        File tempFile = null;
        try {
            QueryWrapper<SupplierSettlement> queryWrapper = new QueryWrapper<SupplierSettlement>().checkSqlInjection();
            //如果是勾选的记录
            if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getIds())) {
                if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getIsHavingByType()) && supplierSettlementExportParam.getIsHavingByType()){
//                    queryWrapper.lambda().in(SupplierSettlement::getSettlementType, supplierSettlementExportParam.getIds().split(","));
                }else{
                    queryWrapper.lambda().in(SupplierSettlement::getId, supplierSettlementExportParam.getIds().split(","));
                }

            }
            if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getBusinessCode())){ //结算单号
                queryWrapper.lambda().like(SupplierSettlement::getBusinessCode, supplierSettlementExportParam.getBusinessCode());
            }
            if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getBusinessBusinessId())) { //业务单号
                queryWrapper.lambda().like(SupplierSettlement::getBusinessBusinessIds, supplierSettlementExportParam.getBusinessBusinessId());
            }
            if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getBusinessSettlementType())) { //结算类型
                queryWrapper.lambda().eq(SupplierSettlement::getBusinessSettlementType, supplierSettlementExportParam.getBusinessSettlementType());
            }
            if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getBusinessObjectId())) {//结算对象
                queryWrapper.lambda().eq(SupplierSettlement::getBusinessObjectId, supplierSettlementExportParam.getBusinessObjectId());
            }
            if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getBusinessShippingStoreId())) {//结算门店
                queryWrapper.lambda().and(i -> i.eq(SupplierSettlement::getBusinessShippingStoreId, supplierSettlementExportParam.getBusinessShippingStoreId()).or().eq(SupplierSettlement::getBusinessStorageStoreId, supplierSettlementExportParam.getBusinessShippingStoreId()));
            }
            if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getBusinessAccountId())) {//结算账户
                queryWrapper.lambda().eq(SupplierSettlement::getBusinessAccountId, supplierSettlementExportParam.getBusinessAccountId());
            }
            if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getBusinessProjectId())) {//结算项目
                queryWrapper.lambda().eq(SupplierSettlement::getBusinessProjectId, supplierSettlementExportParam.getBusinessProjectId());
            }
            if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getBusinessStatus())){ //单据状态
                queryWrapper.lambda().eq(SupplierSettlement::getBusinessStatus, supplierSettlementExportParam.getBusinessStatus());
            }
            //只要结算单或已审核的其它业务单据
            queryWrapper.lambda().and(i -> i.eq(SupplierSettlement::getBusinessType,"JS").or().eq(SupplierSettlement::getBusinessStatus,"1"));
            //查询实付或实收金额大于0的
            queryWrapper.lambda().and(i -> i.gt(SupplierSettlement::getBusinessPayAmount,BigDecimal.ZERO).or().gt(SupplierSettlement::getBusinessInAmount,BigDecimal.ZERO)) ;
            //查询时间范围
            if (ObjectUtil.isNotEmpty(supplierSettlementExportParam.getStartCreateTime()) && ObjectUtil.isNotEmpty(supplierSettlementExportParam.getEndCreateTime())) {
                queryWrapper.lambda().between(SupplierSettlement::getCreateTime, supplierSettlementExportParam.getStartCreateTime() + " 00:00:01", supplierSettlementExportParam.getEndCreateTime() + " 23:59:59");
            }
            //勾选汇总选项
            if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getIsHavingByType()) && supplierSettlementExportParam.getIsHavingByType()){
                String sqlString = "BUSINESS_SETTLEMENT_TYPE,SUM(BUSINESS_TOTAL_AMOUNT) AS BUSINESS_TOTAL_AMOUNT,SUM(BUSINESS_DISCOUNT_AMOUNT) AS BUSINESS_DISCOUNT_AMOUNT,SUM(BUSINESS_PAY_AMOUNT) AS BUSINESS_PAY_AMOUNT,SUM(BUSINESS_IN_AMOUNT) AS BUSINESS_IN_AMOUNT,BUSINESS_STATUS";
                String groupString = "BUSINESS_SETTLEMENT_TYPE,BUSINESS_STATUS";

                if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getIsHavingByStore()) && supplierSettlementExportParam.getIsHavingByStore()) {
                    sqlString = sqlString + ", BUSINESS_SHIPPING_STORE_ID, BUSINESS_STORAGE_STORE_ID";
                    groupString = groupString + ", BUSINESS_SHIPPING_STORE_ID, BUSINESS_STORAGE_STORE_ID";
                }
                if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getIsHavingByAccount()) && supplierSettlementExportParam.getIsHavingByAccount()) {
                    sqlString = sqlString + ", BUSINESS_ACCOUNT_ID";
                    groupString = groupString + ", BUSINESS_ACCOUNT_ID";
                }
                if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getIsHavingByProject()) && supplierSettlementExportParam.getIsHavingByProject()) {
                    sqlString = sqlString + ", BUSINESS_PROJECT_ID";
                    groupString = groupString + ", BUSINESS_PROJECT_ID";
                }
                if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getIsHavingByObject()) && supplierSettlementExportParam.getIsHavingByObject()) {
                    sqlString = sqlString + ", BUSINESS_OBJECT_ID";
                    groupString = groupString + ", BUSINESS_OBJECT_ID";
                }
                queryWrapper.select(sqlString);
                queryWrapper.groupBy(groupString);
            }
            //数据归属
            queryWrapper.lambda().eq(SupplierSettlement::getCompanyId, StpLoginUserUtil.getLoginUser().getCompanyId());
            if(ObjectUtil.isAllNotEmpty(supplierSettlementExportParam.getSortField(), supplierSettlementExportParam.getSortOrder())) {
                CommonSortOrderEnum.validate(supplierSettlementExportParam.getSortOrder());
                queryWrapper.orderBy(true, supplierSettlementExportParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                        StrUtil.toUnderlineCase(supplierSettlementExportParam.getSortField()));
            } else {
                //勾选汇总选项
                if(ObjectUtil.isNotEmpty(supplierSettlementExportParam.getIsHavingByType()) && supplierSettlementExportParam.getIsHavingByType()){
                    supplierSettlementExportParam.setSortField("businessSettlementType");
                    supplierSettlementExportParam.setSortOrder("ascend");
                }else{
                    queryWrapper.lambda().orderByAsc(SupplierSettlement::getId);
                }

            }
            String fileName = (ObjectUtil.isNotEmpty(supplierSettlementExportParam.getIsHavingByType()) && supplierSettlementExportParam.getIsHavingByType()) ? "结算单据（" + supplierSettlementExportParam.getStartCreateTime() + "至" + supplierSettlementExportParam.getEndCreateTime() + "汇总）.xlsx" :  "结算单据（" + supplierSettlementExportParam.getStartCreateTime() + "至" + supplierSettlementExportParam.getEndCreateTime() + "明细）.xlsx";
            List<SupplierSettlement> supplierSettlementList = this.list(queryWrapper);
            if(ObjectUtil.isEmpty(supplierSettlementList)) {
                throw new CommonException("没有符合条件的数据可导出");
            }
            transService.transBatch(supplierSettlementList);
            supplierSettlementList = CollectionUtil.sort(supplierSettlementList, Comparator.comparing(SupplierSettlement::getBusinessSettlementType));
            List<SupplierSettlementExportResult> supplierSettlementExportResults = supplierSettlementList.stream()
                    .map(supplierSettlement -> {
                        SupplierSettlementExportResult supplierSettlementExportResult = new SupplierSettlementExportResult();
                        BeanUtil.copyProperties(supplierSettlement, supplierSettlementExportResult);
                        //如果是付款，则换一下门店名称
                        if(supplierSettlement.getBusinessSettlementType().equals("1")){
                            supplierSettlementExportResult.setBusinessShippingStoreIdName(supplierSettlement.getBusinessStorageStoreIdName());
                        }

                        return supplierSettlementExportResult;
                    }).toList();
            //创建临时文件
            tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
            // 头的策略
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short) 14);
            headWriteCellStyle.setWriteFont(headWriteFont);
            // 水平垂直居中
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 内容的策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
            contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
            // 内容背景白色
            contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            WriteFont contentWriteFont = new WriteFont();

            // 内容字体大小
            contentWriteFont.setFontHeightInPoints((short) 10);
            contentWriteCellStyle.setWriteFont(contentWriteFont);

            //设置边框样式，细实线
            contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
            contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
            contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
            contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);

            // 水平垂直居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
            contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle,
                    contentWriteCellStyle);

            // 写excel
            EasyExcel.write(tempFile.getPath(), SupplierSettlementExportResult.class)
                    // 自定义样式
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    // 自动列宽
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    // 设置第一行字体
                    .registerWriteHandler(new CellWriteHandler() {
                        @Override
                        public void afterCellDispose(CellWriteHandlerContext context) {
                            WriteCellData<?> cellData = context.getFirstCellData();
                            WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
                            Integer rowIndex = context.getRowIndex();
                            if(rowIndex == 0) {
                                WriteFont headWriteFont = new WriteFont();
                                headWriteFont.setFontName("宋体");
                                headWriteFont.setBold(true);
                                headWriteFont.setFontHeightInPoints((short) 11);
                                writeCellStyle.setWriteFont(headWriteFont);
                            }
                        }
                    })
                    // 设置表头行高
                    .registerWriteHandler(new AbstractRowHeightStyleStrategy() {
                        @Override
                        protected void setHeadColumnHeight(Row row, int relativeRowIndex) {
                            if(relativeRowIndex == 0) {
                                // 表头第一行
                                row.setHeightInPoints(20);
                            } else {
                                // 表头其他行
                                row.setHeightInPoints(20);
                            }
                        }
                        @Override
                        protected void setContentColumnHeight(Row row, int relativeRowIndex) {
                            // 内容行
                            row.setHeightInPoints(18);
                        }
                    })
                    .sheet("结算数据")
                    .doWrite(supplierSettlementExportResults);
            CommonDownloadUtil.download(tempFile, response);
        } catch (Exception e) {
            log.error(">>> 结算数据导出异常：", e);
            CommonResponseUtil.renderError(response, "导出失败");
        } finally {
            FileUtil.del(tempFile);
        }

    }
}
